﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

using RTGS.Library;
using RTGS.Library.Entities.Rtgs;
using RTGS.Library.Enum;
using RTGS.Library.Interfaces;


namespace RTGS.Library.DataAccess.Rtgs
{
    public partial class stpConfigRepo : IRepository<stpConfig, string>
    {
        private string errorLog;
        private string connectionString;
        public stpConfigRepo(string ConnectionString)
        {
            errorLog = String.Empty;
            connectionString = ConnectionString;
        }
        public object SelectScalar(SQL.Function.Aggregate function, string column, string parameters)
        {
            object _result = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    StringBuilder sbQuery = new StringBuilder();
                    switch (function)
                    {
                        case SQL.Function.Aggregate.Max:
                            sbQuery.AppendFormat("SELECT MAX({0}) FROM STP_CONFIG {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Min:
                            sbQuery.AppendFormat("SELECT MIN({0}) FROM STP_CONFIG {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Distinct:
                            sbQuery.AppendFormat("SELECT DISTINCT({0}) FROM STP_CONFIG {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Count:
                            sbQuery.AppendFormat("SELECT COUNT({0}) FROM STP_CONFIG {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Sum:
                            sbQuery.AppendFormat("SELECT SUM({0}) FROM STP_CONFIG {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Avg:
                            sbQuery.AppendFormat("SELECT AVG({0}) FROM STP_CONFIG {1}", column, parameters);
                            break;
                        default:
                            // do nothing 
                            break;
                    }

                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        _result = cmd.ExecuteScalar();
                    }
                    catch (Exception ex)
                    {
                        errorLog = ex.Message;
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return _result;
        }
        public List<stpConfig> GetList()
        {
            List<stpConfig> tt = new List<stpConfig>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "SELECT CONFIGNAME, CONFIGVALUE FROM STP_CONFIG";
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                stpConfig t = new stpConfig();
                                t.configname = dr[stpConfig.Fields.configname] == DBNull.Value ? string.Empty : dr[stpConfig.Fields.configname].ToString();
                                t.configvalue = dr[stpConfig.Fields.configvalue] == DBNull.Value ? string.Empty : dr[stpConfig.Fields.configvalue].ToString();
                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        errorLog = ex.Message;
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }
        public List<stpConfig> GetList(int pageSize, int currentPage, string sortName, string sortOrder, string parameters)
        {
            List<stpConfig> tt = new List<stpConfig>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    int startRow = ((currentPage - 1) * pageSize);
                    int endRow = (startRow + pageSize);

                    StringBuilder sbQuery = new StringBuilder();
                    sbQuery.AppendFormat(" SELECT * ");
                    sbQuery.AppendFormat(" FROM (SELECT TOP({0}) ", pageSize);
                    sbQuery.AppendFormat("          r.* ");
                    sbQuery.AppendFormat("       FROM (SELECT TOP({0} + {1} - 1) CONFIGNAME, CONFIGVALUE ", startRow, pageSize);
                    sbQuery.AppendFormat("              FROM STP_CONFIG ");
                    sbQuery.AppendFormat("             {0} ", parameters);
                    sbQuery.AppendFormat("              ORDER BY {0} {1}) r ", sortName, sortOrder);
                    sbQuery.AppendFormat("       ORDER BY {0} DESC) r ", sortName);
                    sbQuery.AppendFormat(" ORDER BY {0}", sortName);

                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                stpConfig t = new stpConfig();
                                t.configname = dr[stpConfig.Fields.configname] == DBNull.Value ? string.Empty : dr[stpConfig.Fields.configname].ToString();
                                t.configvalue = dr[stpConfig.Fields.configvalue] == DBNull.Value ? string.Empty : dr[stpConfig.Fields.configvalue].ToString();
                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        errorLog = ex.Message;
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }
        public stpConfig GetById(string key)
        {
            stpConfig t = new stpConfig();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "SELECT CONFIGNAME, CONFIGVALUE FROM STP_CONFIG WHERE CONFIGNAME = @configname";
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@configname", SqlDbType.VarChar).Value = key;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                t.configname = dr[stpConfig.Fields.configname] == DBNull.Value ? string.Empty : dr[stpConfig.Fields.configname].ToString();
                                t.configvalue = dr[stpConfig.Fields.configvalue] == DBNull.Value ? string.Empty : dr[stpConfig.Fields.configvalue].ToString();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        errorLog = ex.Message;
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return t;
        }
        public bool Save(stpConfig domain)
        {
            bool result = false;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "INSERT INTO STP_CONFIG(CONFIGNAME, CONFIGVALUE) VALUES(@configname, @configvalue)";
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@configname", SqlDbType.VarChar).Value = domain.configname;
                    cmd.Parameters.Add("@configvalue", SqlDbType.VarChar).Value = domain.configvalue;

                    try
                    {
                        conn.Open();
                        cmd.ExecuteNonQuery();
                        result = true;
                    }
                    catch (Exception ex)
                    {
                        errorLog = ex.Message;
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }

                }
            }
            return result;
        }
        public bool Update(stpConfig domain)
        {
            int result = 0;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "UPDATE STP_CONFIG SET CONFIGNAME = @configname, CONFIGVALUE = @configvalue WHERE CONFIGNAME = @configname";
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@configname", SqlDbType.VarChar).Value = domain.configname;
                    cmd.Parameters.Add("@configvalue", SqlDbType.VarChar).Value = domain.configvalue;

                    try
                    {
                        conn.Open();
                        result = cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        errorLog = ex.Message;
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return (result > 0);
        }
        public bool Delete(string key)
        {
            bool result = false;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "DELETE FROM STP_CONFIG WHERE CONFIGNAME = @configname";
                    cmd.CommandType = CommandType.Text;



                    cmd.Parameters.AddWithValue("@configname", key);// SqlDbType.Int).Value = key;




                    try
                    {
                        conn.Open();
                        cmd.ExecuteNonQuery();
                        result = true;
                    }
                    catch (Exception ex)
                    {
                        errorLog = ex.Message;
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return result;
        }
        public string GetErrorMessage()
        {
            return errorLog;
        }

    }
}
